﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using HtmlExtractor.XPathOutput;
using System.Xml.Linq;

namespace HtmlExtractor.Output
{
    public class XDocumentOutput : IOutput<XDocument>
    {
        public XDocumentOutput()
        { }
        public XDocumentOutput(XDocument template)
        {
            Template = template;
        }
        public XDocument Template
        { get; set; }

        public XPathOutputPathProcessorChain ProcessorChain
        {
            get;
            set;
        }
        #region IOutput<XElement> Members
        private bool HasOutputPath(List<string> path)
        {
           return path.Where(p => !string.IsNullOrEmpty(p)).Count()>=1;
        }
        public bool TryGetOutPutResult(PageResult result,out XDocument doc)
        {
            doc = Template;
            if (result == null)
                return false;
            if (Template == null)
            {
                return false;
            }
            
            foreach (IGrouping<List<string>, IPageItem> grouping in result.GroupByOutputPath())
            {

                if (HasOutputPath(grouping.Key))
                {
                    if (ProcessorChain == null)
                    {
                        ProcessorChain = XPathOutputPathProcessorChain.DefaultChain(grouping);
                    }
                    else
                    {
                        foreach (XmlDocOutputPathProcessor p in ProcessorChain)
                        {
                            p.InputData = grouping;
                        }
                    }
                    ProcessorChain.Process(ref doc);
                }
            }
            return true;

        }
        #endregion
    }
}
